<template>
  <el-dialog :close-on-click-modal="false" :title="form.id ? t('common.editBtn') : t('common.addBtn')" width="600"
             draggable v-model="visible">
    <el-form :model="form"  ref="dataFormRef" label-width="100px" :rules="dataRules" v-loading="loading">
        <el-form-item :label="t('aigcModel.apiKey')" prop="apiKey">
            <el-input v-model="form.apiKey" :placeholder="t('aigcModel.inputApiKeyTip')" clearable ></el-input>
        </el-form-item>
        <el-form-item :label="t('aigcModel.secretKey')" prop="secretKey">
            <el-input v-model="form.secretKey" :placeholder="t('aigcModel.inputSecretKeyTip')" readonly clearable >
            </el-input>
        </el-form-item>
        
        <el-form-item :label="t('aigcAppApi.channel')" prop="channel">
          <el-select v-model="form.channel" :placeholder="t('aigcAppApi.inputChannelTip')">
              <el-option v-for="item in channelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>  
        <el-form-item :label="t('aigcModel.remark')" prop="remark">
            <el-input type="textarea" rows="5" v-model="form.remark" :placeholder="t('aigcModel.inputRemarkTip')" clearable>
            </el-input>
        </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible=false">{{ t('common.cancelButtonText') }}</el-button>
        <el-button @click="onSubmit" type="primary" :disabled="loading">{{ t('common.confirmButtonText') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="aigcModelChatDialog" setup>
import { useI18n } from 'vue-i18n';
import { addObj, getObj, putObj } from '/@/api/aigc/appApi';
import { useMessage } from '/@/hooks/message';
import { useAppStore } from '/@/stores/aigc/appStore';
import { decrypt, encrypt, generateKey } from '/@/utils/keyTool';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const {t} = useI18n();

const channelList=[{
  value:'API',
  label:'CHANNEL_API'
}];
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const appStore=useAppStore();
// 提交表单数据
const form = reactive({
      id:'',
      appId:'',
      apiKey:'',
      apiKeyEncrypt:'',
      secretKey:'',
      channel:'',
      remark:'',
});

// 定义校验规则
const dataRules = ref({
    appId: [
      {required: true, message: '应用ID能为空', trigger: 'blur'},
    ],
    channel: [
      {required: true, message: '渠道不能为空', trigger: 'blur'},
    ],
    apiKey: [
      {required: true, message: 'apiKey不能为空', trigger: 'blur'},
    ],
});

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  form.id = '';

  nextTick(() => {
    dataFormRef.value.resetFields();
  });
  //
  getAppInfo();
  // 获取信息
  if (id) {
    form.id = id;
    getData(id);
  }
};

const getAppInfo=()=>{
  const appId=appStore.info.id;
  form.appId=appId;
  form.secretKey=appStore.info?.model.secretKey;
}


// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    //更新加密密钥
    if(form.apiKey&&form.apiKey!==""&&form.apiKey!=='******'&&form.secretKey&&form.secretKey!==""){
        let apiKey=form.apiKey;
        let secretKey = form.secretKey;
        form.apiKeyEncrypt = encrypt(apiKey,secretKey);
        form.apiKey = form.apiKeyEncrypt;
    }
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 初始化数据
const getData = (id: string) => {
  getObj(id).then((res: any) => {
    Object.assign(form, res.data);
    //解密
    if(form.apiKey&&form.apiKey!==""&&form.apiKey!=='******'&&form.secretKey&&form.secretKey!==""){
        let apiKey=form.apiKey;
        let secretKey = form.secretKey;
        form.apiKey=decrypt(form.apiKey,secretKey);
    }
  });
};
//生成随机密钥
const generateSecretKey=()=>{
    form.secretKey = generateKey(16);
}
// 暴露变量
defineExpose({
  openDialog,
});
</script>